﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.Models;
using Code.BLL;
using QianBuo.Lottery.Web.Commen;
using QianBuo.Lottery.Web.Areas.Manage.Models.CardsModels;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    [Authorize(Roles = "Manager_Account_AddMoney")]
    public class CardsController : BaseController
    {
        CardManage CM = new CardManage();

        public ActionResult Index(IndexModel model)
        {
            if (model == null)
                model = new IndexModel();
            if (model.Search == null)
                model.Search = new CardSearchModel();
            if (model.Page == null || model.Page < 1)
                model.Page = 1;
            if (model.PageSize == null || model.PageSize < 1)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);

            model.States = (Enum.GetValues(typeof(CardState)) as CardState[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString(), Selected = model.Search.State == p }).ToList();
            model.States.Insert(0, new SelectListItem { Text = "选择状态", Value = "" });
            model.DownTypes = new List<SelectListItem>();
            model.DownTypes.Add(new SelectListItem { Text = "当前选中", Value = "3", Selected = model.DownType == "3" });
            model.DownTypes.Add(new SelectListItem { Text = "当前页面", Value = "2", Selected = model.DownType == "2" });
            model.DownTypes.Add(new SelectListItem { Text = "当前条件", Value = "1", Selected = model.DownType == "1" });


            var data = CM.FindCard(model.Search);
            model.SumCount = data.Count();
            model.Cards = data.Skip(model.PageSize.Value * (model.Page.Value - 1)).Take(model.PageSize.Value).ToArray()
                .Each(p => p.Password = CardManage.DecryptPwd(p.Password));
            
            return View("Index",model);
        }

        [ActionName("Index"),MultiButton("AddCard")]
        public ActionResult AddCard(IndexModel model)
        {
            if (model == null)
                ModelState.AddModelError("Error", "参数不正确");
            else if (!model.AddCount.HasValue)
                ModelState.AddModelError("AddCount", "*");
            else if (!model.Money.HasValue)
                ModelState.AddModelError("Money", "*");
            if (ModelState.IsValid)
            {
                int rs = CM.AddCard(model.Money.Value, model.AddCount.Value);
                if (rs < 0)
                    ViewData["msg"] = "添加失败,请稍后再试。".AlertOffPage();
                else
                    ViewData["msg"] = "成功添加{0}张点卡".Format(rs).AlertOffPage();
            }

            return Index(model);
        }

        [ActionName("Index"), MultiButton("DownLoad",Argument="Page")]
        public ActionResult DownLoad(IndexModel model, string[] choose)
        {
            if (model == null)
                ModelState.AddModelError("Error", "参数不正确");
            else if (model.DownType == "3" && (choose == null || choose.Length == 0))
                ModelState.AddModelError("DownType", "无选中");
            else if (model.DownType != "3" && model.Search.State == CardState.Used)
                ModelState.AddModelError("Search.State", "*");
            if (ModelState.IsValid)
            {
                if (model.Page == null || model.Page < 1)
                    model.Page = 1;
                if (model.PageSize == null || model.PageSize < 1)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);

                IEnumerable<CardManage.CardItem> data = null;
                switch (model.DownType)
                {
                    case "1":
                        data = CM.FindCard(model.Search);
                        break;
                    case "2":
                        data = CM.FindCard(model.Search).Skip(model.PageSize.Value * (model.Page.Value - 1)).Take(model.PageSize.Value);
                        break;
                    case "3":
                        data = CM.FindCard(null).Where(p => choose.Contains(p.Number));
                        break;
                }

                if (data == null)
                    ModelState.AddModelError("DownType", "*");
                else
                {
                    var t = data.Where(p => p.State == CardState.Normal).ToArray();
                    if (t.Length == 0)
                    {
                        ViewData["msg"] = "没有找到符合条件的点卡".AlertOffPage();
                    }
                    else
                    {
                        WriteCard(t);
                    }
                }
            }

            return Index(model);
        }

        private void WriteCard(CardManage.CardItem[] t)
        {
            var groupdata = t.GroupBy(p => new { p.Money });
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";//问题就在这里，解决百M关口 
            Response.AddHeader("Content-Disposition", "attachment; filename=Card_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            groupdata.Each(p =>
            {
                Response.Write("             卡号                       密码       价格：" + p.Key.Money.ToString("C") + "元(" + p.Count() + "张)\r\n");
                p.Each(pp =>
                {
                    Response.Write(pp.Number + "       " + CardManage.DecryptPwd(pp.Password) + "\r\n");
                });
                Response.Write("\r\n");
            });
            Response.Write("                                                   合计:" + t.Length + "张");
            Response.End();
        }

        [ActionName("Index"), MultiButton("DelCard",Argument="Page")]
        public ActionResult DelCard(IndexModel model, string[] choose)
        {
            if (model == null)
                ModelState.AddModelError("Error", "参数不正确");
            else if (model.DownType == "3" && (choose == null || choose.Length == 0))
                ModelState.AddModelError("DownType", "无选中");
            else if (model.DownType != "3" && model.Search.State == CardState.Used)
                ModelState.AddModelError("Search.State", "*");
            if (ModelState.IsValid)
            {
                if (model.Page == null || model.Page < 1)
                    model.Page = 1;
                if (model.PageSize == null || model.PageSize < 1)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);
                IEnumerable<CardManage.CardItem> data = null;
                switch (model.DownType)
                {
                    case "1":
                        data = CM.FindCard(model.Search);
                        break;
                    case "2":
                        data = CM.FindCard(model.Search).Skip(model.PageSize.Value * (model.Page.Value - 1)).Take(model.PageSize.Value);
                        break;
                    case "3":
                        data = CM.FindCard(new CardManage.CardSearchModel { State = CardState.Normal }).Where(p => choose.Contains(p.Number));
                        break;
                }

                if (data == null)
                    ModelState.AddModelError("DownType", "*");
                else
                {
                    var t = data.Where(p => p.State == CardState.Normal).Select(p => p.Number);
                    int rs = CM.Del(t);
                    if (rs < 0)
                        ViewData["msg"] = "操作失败，请稍后再试。".AlertOffPage();
                    else
                        ViewData["msg"] = "成功删除{0}张点卡".Format(rs).AlertOffPage();
                }
            }

            return Index(model);
        }


    }
}
